// pages/goods_list/goods_list.js
// 导入获取数据的方法
import { request } from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs: [
            {
                id: 0,
                value: '综合',
                isActive: true
            },
            {
                id: 1,
                value: '销量',
                isActive: false
            },
            {
                id: 2,
                value: '价格',
                isActive: false
            }
        ],
        goodsList: []
    },
    // 设置数据要的参数
    QueryParams: {
        query: "",
        cid: "",
        pagenum: 1,
        pagesize: 10
    },
    // 总页数
    totalPages: 1,
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.QueryParams.cid = options.cid || ""
        this.QueryParams.query = options.query || ""

        this.getGoodsList()
    },
    /**
     * 生命周期函数--监听上拉触底
     */
    onReachBottom() {
        if (this.QueryParams.pagenum >= this.totalPages) {
            wx.showToast({
                title: '人家是有上限的',
                icon: 'error'
            })
        } else {
            this.QueryParams.pagenum++
            this.getGoodsList()
        }
    },
    /**
     * 生命周期函数--监听下拉刷新
     */
    onPullDownRefresh() {
        // 重置数据
        this.setData({
            goodsList: []
        })
        // 重置页码
        this.QueryParams.pagenum = 1
        // 重新发送请求
        this.getGoodsList()
    },
    // 获取数据
    async getGoodsList() {
        const result = await request({ url: '/goods/search', data: this.QueryParams })
        const total = result.total
        this.totalPages = Math.ceil(total / this.QueryParams.pagesize)
        this.setData({
            goodsList: [...this.data.goodsList, ...result.goods]
        })
        // 关闭下拉刷新窗口
        wx.stopPullDownRefresh()
    },
    // 点击标题切换事件
    bindTabsItemChange(e) {
        const { index } = e.detail
        let { tabs } = this.data
        tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
        this.setData({
            tabs
        })
    }
})